/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package itopiamme;

import java.io.IOException;
import com.phidgets.InterfaceKitPhidget;
import com.phidgets.PhidgetException;
import com.phidgets.event.InputChangeEvent;
import com.phidgets.event.InputChangeListener;
import expo43server.Expo43GameServer;
import expo43server.Expo43GameStartingServer;
import expo43server.Expo43Server;

/**
 *
 * @author TommySprat
 */
public class PhidgetHandler implements Runnable, InputChangeListener {

    private InterfaceKitPhidget iface;
    private static final int FILM_PREV_INPUT = 4;//Digital phidget input port for startbutton and previousbutton
    private static final int GAME_NEXT_INPUT = 7;//Digital phidget input port for gamebutton and nextbutton
    private static final int STOP_BREAK_INPUT = 2; //Digital phidget input port for stopbutton and breakloopbutton
    private boolean pressed = false;
    private boolean gameRunning = false;
    private boolean introLoopRunning = false;
    private boolean filmRunning = false;
    private expo43server.Expo43Server e43Server;
    private expo43server.Expo43GameServer e43GameServer;
    private Expo43GameStartingServer e43GameStartingServer;
    private VLCv2 vlcController;
    private String vlcNowPlaying = "";

    public void run() {

        e43GameStartingServer = new Expo43GameStartingServer(this);
        e43GameStartingServer.start();
        try {
            e43Server = new expo43server.Expo43Server();
        } catch (IOException exc) {
            System.out.println("Expo43Server I/O Error");
            exc.printStackTrace();
        }
        this.createConnections();
        this.iface.addInputChangeListener(this);

        try {
            while (true) {
                Thread.sleep(1);

                //System.out.println("Still running :D" + Math.random());
                if (filmRunning) {
                    String vlcWasPlaying = vlcNowPlaying;

                    vlcNowPlaying = vlcController.info.getTitle();

                    try {
                        /*A new scene is playing if it's name is different from the previous
                         * scene's name 
                         * AND the length of the scene name must be longer than 4
                         * second because VLC inserts some esoteric "scene" between two real scenes
                         * that has no name
                         */
                        if (!vlcWasPlaying.equals(vlcNowPlaying) & vlcNowPlaying.length() > 4) {
                            System.out.println("A new video started playing: " + vlcNowPlaying);
                            e43Server.setScene(vlcNowPlaying);
                        }
                    } catch (NullPointerException exc) {
                        //VLC has closed itself causing a NullPointerException
                        vlcController.disconnect();
                        e43Server.stopPlaylist();
                        filmRunning = false;
                    }
                }
                if (introLoopRunning) {
                    if (vlcController.info.getTitle() == null){
                        //When VLC is closed getTitle returns null
                        introLoopRunning = false;
                        System.out.println("Introloop is done");
                    }
                }
            }
        } catch (InterruptedException e) {
        }

    }

    protected void createConnections() {
        try {
            iface = new InterfaceKitPhidget();
            iface.openAny();
            iface.waitForAttachment(1000);
        } catch (PhidgetException e) {
            System.err.println("unable to connect to Phidget! " + e);
            System.exit(1);
        }
    }

    public void inputChanged(InputChangeEvent ice) {
        if (pressed == false) {
            switch (ice.getIndex()) {
                case FILM_PREV_INPUT:
                    if (!gameRunning && !filmRunning && !introLoopRunning) {
                        startFilm();
                        break;
                    }
                    if (filmRunning && !gameRunning && !introLoopRunning) {
                        vlcController.rc.prev();
                        break;
                    }
                    break;
                case GAME_NEXT_INPUT:
                    if (!gameRunning && !filmRunning && !introLoopRunning) {
                        startGame();
                        break;
                    }
                    if (filmRunning && !gameRunning && !introLoopRunning) {
                        vlcController.rc.next();
                        break;
                    }
                case STOP_BREAK_INPUT:
                    if (filmRunning && !gameRunning && !introLoopRunning) {
                        vlcController.rc.clear();
                        vlcController.rc.enqueue("C:\\Expo43Menu\\stop.m3u");
                        vlcController.rc.play();
                        break;
                    }
                    if (!gameRunning && !filmRunning && !introLoopRunning) {
                        startIntroLoop();
                        break;
                    }
                    if (introLoopRunning && !gameRunning && !filmRunning) {
                        vlcController.rc.pause();
                        if (vlcController.info.getTitle().equalsIgnoreCase("IntroLoop.wmv")){
                            vlcController.rc.next();
                        }
                        break;
                    }
                    break;
            }
        }
        pressed = !pressed;
    }

    private void startIntroLoop() {
        if (gameRunning == true || filmRunning == true || introLoopRunning == true) {
            return;//only needs to be called once for an entire session
        }
        System.out.println("Start de 'IntroLoop'");
        try {
            Process proc = Runtime.getRuntime().exec("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe");
        } catch (IOException ex) {
            System.out.println("Problem with starting VLC (check if it's installed in the default path)");
        }
        // Create a VLCv2 object and make it connect to VLC:
        vlcController = new VLCv2("localhost", 1234, false);
        vlcController.connect();
        // Clear the playlist, enqueue playlist and play:
        vlcController.rc.clear();
        vlcController.rc.enqueue("C:\\Expo43Menu\\IntroLoop.m3u");
        vlcController.rc.fullscreen();
        //sleep(3000);
        vlcController.rc.play();
        //Start from the beginning and pause
        vlcController.rc.seek(0);
        vlcController.rc.pause();
        introLoopRunning = true;
    }

    private void startGame() {
        if (gameRunning == true || filmRunning == true || introLoopRunning == true) {
            return;//only needs to be called once for an entire session
        }
        System.out.println("Starting ExpoGame");
        e43Server.startGame();
        e43GameServer = new Expo43GameServer(this);
        e43GameServer.start();
        //GAME STARTER
        /*try {
            Process proc = Runtime.getRuntime().exec("C:\\Expo43Menu\\python.bat");
        } catch (IOException ex) {
            System.out.println("Problem with starting the game");
        }*/
        e43GameStartingServer.startGame();
        gameRunning = true;
    }

    private void startFilm() {
        if (gameRunning == true || filmRunning == true || introLoopRunning == true) {
            return;//only needs to be called once for an entire session
        }
        System.out.println("Start de ITopia filmtour");

        /* VLC STARTER
         * VLC Versie gebruiken die is geleverd bij de workshop. (kopie installie staat in "C:\Expo43Menu")
         * VLC KILLER: Extra>Voorkeuren>"alle opties aanvinken">afspeellijst>"dan (afspelen en sluiten) AANvinken."
         * VLC REMOTE CONTROL: Extra>Voorkeuren>"alle opties aanvinken">Interface>
         * "dan Afstandbediening interface AANvinken">"doorgaan naar subtab Afstandbediening">
         * "dan (Open geen dos commando box interface) AANvinken">"Dan bij TCP commando invoer:0.0.0.0:1234 invullen".
         * Nu is VLC goed ingesteld voor de MME. NOTE: zorg dat 'repeat all en shuffle' uitstaan voor de playlist.
         */
        try {
            Process proc = Runtime.getRuntime().exec("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe");
        } catch (IOException ex) {
            System.out.println("Problem with starting VLC (check if it's installed in the default path)");
        }
        // Actie wanneer er geklikt wordt op de ITopia demo knop.
        // Create a VLCv2 object and make it connect to VLC:
        vlcController = new VLCv2("localhost", 1234, false);
        vlcController.connect();
        // Clear the playlist, enqueue playlist and play:
        vlcController.rc.clear();
        vlcController.rc.enqueue("C:\\Expo43Menu\\playlist.m3u");
        vlcController.rc.fullscreen();
        //sleep(3000);
        vlcController.rc.play();
        //System.out.println(vlcController.getPlayState());
        //Start from the beginning
        vlcController.rc.seek(0);
        //vlcController.disconnect();
        e43Server.setScene(vlcController.info.getTitle());
        vlcNowPlaying = vlcController.info.getTitle();
        e43Server.startPlaylist();
        filmRunning = true;
    }

    public void stopGame() {
        e43Server.stopGame();
        setGameRunning(false);
    }

    public void setGameRunning(boolean state) {
        gameRunning = state;
    }

    public void setFilmRunning(boolean state) {
        filmRunning = state;
    }
}
